import { defineStore } from 'pinia'
import { userApi, type UserInfo } from '@/api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: null as UserInfo | null,
    isLoggedIn: false
  }),

  getters: {
    isAuthenticated: (state) => !!state.token && state.isLoggedIn,
    username: (state) => state.userInfo?.username || '',
    userType: (state) => state.userInfo?.userType || 1
  },

  actions: {
    // 设置token
    setToken(token: string) {
      this.token = token
      this.isLoggedIn = true
      localStorage.setItem('token', token)
    },

    // 清除token
    clearToken() {
      this.token = ''
      this.isLoggedIn = false
      this.userInfo = null
      localStorage.removeItem('token')
    },

    // 登录
    async login(username: string, password: string) {
      try {
        const token = await userApi.login({ username, password })
        this.setToken(token)
        await this.fetchUserInfo()
        return true
      } catch (error) {
        this.clearToken()
        throw error
      }
    },

    // 注册
    async register(data: any) {
      await userApi.register(data)
    },

    // 获取用户信息
    async fetchUserInfo() {
      if (!this.token) return
      
      try {
        const userInfo = await userApi.getUserInfo()
        this.userInfo = userInfo
      } catch (error) {
        this.clearToken()
        throw error
      }
    },

    // 登出
    logout() {
      this.clearToken()
    },

    // 初始化用户状态
    async initUser() {
      if (this.token) {
        try {
          await this.fetchUserInfo()
          this.isLoggedIn = true
        } catch (error) {
          this.clearToken()
        }
      }
    }
  }
})